package com.xuecheng.content.service.impl;

import com.xuecheng.api.content.model.qn.UploadTokenResult;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.content.common.constant.ContentErrorCode;
import com.xuecheng.content.service.FileManagerService;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class FileManagerServiceImpl implements FileManagerService {

    @Autowired
    private RestTemplate restTemplate;

    //文件管理系统-获取上传凭证地址
    @Value("${file.service.url}")
    private String url;
    //储存空间名称
    @Value("${file.service.bucket}")
    private String bucketName;
    //存储区域地址
    @Value("${file.service.upload.region}")
    private String region;
    //cdn域名
    @Value("${cdn.domain}")
    private String domain;

    /*
    从文件系统那边获取七牛云上传凭证
    条件从 Nacos 配置文件中获取七牛云的所需信息 url，储存空间名称，存储区域地址，cdn域名
    通过 restTemplate 调用url 获取上传凭证信息， 判断 上传凭证信息 是否为空
    并将上传凭证中的信息 放入 UploadTokenResult 类中 返回给前端
     */
    public UploadTokenResult getUploadToken() {

        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("scope",bucketName);
        hashMap.put("deadline",3600);
        hashMap.put("tokenType","1");
        String fileKey = UUID.randomUUID().toString()+
                RandomStringUtils.randomAlphanumeric(32);
        hashMap.put("key", fileKey);

        ResponseEntity<Map> mapResponseEntity = restTemplate.postForEntity(url,hashMap,Map.class);
        Map body = mapResponseEntity.getBody();

        if (ObjectUtils.isEmpty(body)){
            ExceptionCast.cast(ContentErrorCode.E_120601);
        }

        UploadTokenResult tokenResult = new UploadTokenResult();
        tokenResult.setQnToken(body.get("result").toString());
        tokenResult.setTokenType(hashMap.get("tokenType").toString());
        tokenResult.setDeadline(new Integer(hashMap.get("deadline").toString()));
        tokenResult.setScope(bucketName);
        tokenResult.setKey(hashMap.get("key").toString());
        tokenResult.setUp_region(region);
        tokenResult.setDomain(domain);


        return tokenResult;
    }
}
